package com.artisan.web.action;

import com.alibaba.fastjson.JSON;
import com.artisan.common.pojo.ApiRes;
import com.artisan.medium.wx.pojo.AccessToken;
import com.artisan.medium.wx.service.WxMessageService;
import com.artisan.medium.wx.service.WxUserService;
import com.artisan.medium.wx.utils.AccessTokenUtils;
import com.artisan.model.Customer;
import com.artisan.model.CustomerMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by yang on 2017/6/24.
 */
@Controller
@RequestMapping("wx/msg/")
public class WxMessageController {
    @Autowired
    private WxUserService wxUserService;
    @Autowired
    private WxMessageService wxMessageService;
    @RequestMapping("suggest")
    public ModelAndView message(HttpServletRequest request, HttpServletResponse response) throws Exception {
        return new ModelAndView("suggest");
    }

    /**
     * 保存用户留言
     * @param request
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "addMessage",method = RequestMethod.GET)
    public String saveMesssage(HttpServletRequest request) throws Exception {
        Map<String, Object> resultData = new HashMap<String, Object>();
        AccessToken at=null;
        if(request.getSession().getAttribute("TOKEN")!=null){
            at=(AccessToken) request.getSession().getAttribute("TOKEN");
        }
        String openid = at.getOpenid();
        Customer customer=wxUserService.getCustomerByOpenId(openid);
        if(customer==null){
            resultData.put("result", ApiRes.ERROR_CODE);
        }else{
            String msg=request.getParameter("msg");
            CustomerMessage message=new CustomerMessage();
            message.setuId(customer.getId());
            message.setMessage(msg);
            message.setCreateTime(new Date());
            wxMessageService.addMessage(message);
            resultData.put("result", ApiRes.SUCCESS_CODE);
        }
        return JSON.toJSONString(resultData);
    }
}
